package model.drawServer.Implement;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import model.drawPanel.*;
import model.drawPanel.entitys.*;
import model.roomManagement.Implementation.Server;
/*
 * 负责管理单个房间的消息的记录，权限的管理，消息的转发
 * 
 */
public class DrawRoom implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 101250130L;
//	private transient DrawServer ds;
	private transient ArrayList<ClientProxy> clientList;
	private transient String chairmanIP;
	private int entityCounter;
	//---------------------------------------
	private int roomID;
	private int panelNum =0;//被选中的
	private  ArrayList<Entity> entityList;
	private ArrayList<Entity>penList;
	private ArrayList<Panel>panelList;
	private ArrayList<DrawOrder>orderList;
	private ArrayList<DrawOrder>redoList;
	private transient DrawOrder temp_order;//=null 标识本次为新的指令开始
	private int num=0;
	//--------------------------------------------------
	public DrawRoom(int roomID) {
		super();
		this.roomID = roomID;
		clientList = new ArrayList<ClientProxy>();
		panelList = new ArrayList<Panel>();
		Panel p = new Panel();
		panelList.add(p);
		penList = p.getPenList();
		entityList = p.getEntitList();
		orderList = p.getOrderList();
		redoList = p.getRedoList();
		temp_order = null;
	//	this.ds = ds;
		
	}
/*	public DrawRoom(int roomID,ArrayList<Panel>panelList){
		this.roomID = roomID;
		clientList = new ArrayList<ClientProxy>();
		this.panelList =panelList;
		Panel p =panelList.get(0);
		penList = p.getPenList();
		entityList = p.getEntitList();
		orderList = p.getOrderList();
		redoList = p.getRedoList();
		temp_order = null;
	}
	*/
	
	public int getRoomID() {
		return roomID;
	}
	public void setRoomID(int roomID) {
		this.roomID = roomID;
	}
	public void receiveMsg(Order order,InetAddress sendAddr){ 
		if(order.getType() == 0){
			sendToOther(order,sendAddr);
		}
		else if(order.getType() == 1){//operation
			OperationOrder oo = (OperationOrder)order;
			String msg =oo.getMsg();
			if(msg.startsWith(OperationOrder.AUTHORITY_REQUEST)){
				if(chairmanIP ==null||clientList.size()==0){
					chairmanIP=msg.substring(16);
					System.out.println("ip is request by=----------------------"+chairmanIP);
					sendToAll(new OperationOrder(this.roomID,OperationOrder.AUTHORITY_PASS+chairmanIP));
				}else{
					for(ClientProxy cp:clientList){
						if(cp.getAddr().getHostAddress().toString().equals(sendAddr.getHostAddress().toString())){
							cp.send(new OperationOrder(this.roomID,OperationOrder.AUTHORITY_PASS+chairmanIP));
						}
					}
				}
				return;
			}else if(msg.startsWith(OperationOrder.AUTHORITY_PASS)){
				chairmanIP = msg.substring(9);
				System.out.println("ip is pass to=----------------------"+chairmanIP);
				if(chairmanIP.equals("0")){//放弃
					chairmanIP =null;
				}
				sendToAll(order);
			}else{
				sendToOther(order, sendAddr);
			}
				
		}
		orderDeal(order);
	/*
	 * 处理跟绘图板有关的指令或操作
	 */
	}
	private void orderDeal(Order order){
		//operation
		System.out.println(num++);
		if(order.getType()==1){
				
				if(order.getClass().getName().equals("model.drawPanel.OperationOrder")){
				OperationOrder oo = (OperationOrder)order;
				String msg = oo.getMsg();
				if(msg.startsWith(OperationOrder.ADD_PANEL)){
					 panelList.add(new Panel());
					 return;
				}
				if(msg.startsWith(OperationOrder.DELETE_PANEL)){
					int index =Integer.valueOf(msg.substring(11));
				    panelList.remove(index);
				    if(panelList.size()==0){
						 Panel p = new Panel();
						 entityList = p.getEntitList();
						 penList = p.getPenList();
						 orderList =p.getOrderList();
						 redoList = p.getRedoList();
						 entityCounter =0;
						 panelList.add(p);
						 panelNum=0;
					}
				    return;
				}
				if(msg.startsWith(OperationOrder.CHOOSE_PANEL)){
	
					 int id = Integer.valueOf(msg.substring(11));
					 panelNum = id;
					entityList = panelList.get(id).getEntitList();
					penList = panelList.get(id).getPenList();
					orderList =panelList.get(id).getOrderList();
					redoList = panelList.get(id).getRedoList();
					return;
				}
				if(msg.startsWith(OperationOrder.REDO)){
					 int index = redoList.size()-1;
					 if(index<0){
						 return;
					 }
					 DrawOrder temp =redoList.get(index);
					
					 if(temp.getDrawType()==1){
					 temp.execute(entityList);
					 }else{
						 temp.execute(penList);
					 }
					 orderList.add(temp);
					 redoList.remove(index);
					 return;
				}if(msg.startsWith(OperationOrder.UNDO)){
					 int index =orderList.size()-1;
					 if(index <0){
						 return;
					 }
					 DrawOrder temp =orderList.get(index);
					 if(temp.getDrawType()==1){
					 temp.undo(entityList);
					 }else{
						 temp.undo(penList);
					 }
					 redoList.add(temp);
					 orderList.remove(index);
					 return;
				}if(msg.startsWith(OperationOrder.SAVE)){
				//	Server.getDB().addFile(file, roomID, 0);//0代表公有了
				}
			}
		}
		//draw
		else{
			//change 信息
			 if(order.getClass().getName().equals("model.drawPanel.DrawOrder_Change")){
				DrawOrder_Change change = (DrawOrder_Change)order;
				temp_order.change(change.x	, change.y);
			}
		 //drawOrder
			else{
				DrawOrder drawOrder = (DrawOrder)order;
		//drawOrder分隔符
				if(drawOrder.getId() == -1){
					if(temp_order==null){
						System.out.println("add null to orderList");
					}
					orderList.add(temp_order);
					temp_order =null;
					return;
				}
		//新的drawOrder	
				else{
					temp_order = drawOrder;
					if(temp_order.getClass().getName().equals("model.drawPanel.DrawOrder_ADD")){
						entityCounter++;
					}
				}	
			}
			if(temp_order.getDrawType()==0){
				temp_order.execute(penList);
			}else{
			temp_order.execute(entityList);
			}
		}//
    }
	public void userEnter(ClientProxy cp){
		clientList.add(cp);
		cp.addToRoom(this);
		cp.send(new IniteOrder(this.panelNum,this.panelList,this.temp_order,chairmanIP,entityCounter));
	}
	public void userLeave(InetAddress addr){
	
		ClientProxy del=null;
		for(ClientProxy client:clientList){
			if(client.getAddr().getHostAddress().toString().equals(addr.getHostAddress().toString())){
				del =client;
			}
		}
		
		clientList.remove(del);
		if(del.getAddr().getHostAddress().toString().equals(chairmanIP)){
			chairmanIP =null;
			sendToAll(new OperationOrder(roomID, OperationOrder.AUTHORITY_PASS + "0"));
		}
		
	}
	private void sendToAll(Order order){
		for(ClientProxy client:clientList){
			client.send(order);
			
		}
		
		
	}
	private void sendToOther(Order order,InetAddress senderAddr){
		for(ClientProxy client:clientList){
			if(client.getAddr().getHostAddress().toString().equals(senderAddr.getHostAddress().toString())){
				continue;
			}
			client.send(order);
			
		}
	
	}


	public void setDs(DrawServer ds) {
	//	this.ds = ds;
		clientList = new ArrayList<ClientProxy>();
	}
	
}

